import asyncio

import smtplib
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
# 发件人邮箱地址
from email.utils import formataddr

async def main():
    username = 'postmaster@zhaixiaozhi.com'
    # 发件人邮箱密码
    password = 'zxz@2023'
    # 自定义的回复地址
    replyto = 'postmaster@zhaixiaozhi.com'

    From = formataddr(["自定义发信昵称", '195505183@qq.com'])  # 昵称+发信地址(或代发)
    to = ','.join(['', ''])

    cc = ''
    bcc = ''

    # 收件人地址或是地址列表，支持多个收件人
    rcptto = [to, cc, bcc]

    # msg是邮件需要显示的信息
    msg = MIMEMultipart('alternative')
    msg['Subject'] = Header('smtp发信测试')
    msg['from'] = From
    msg['rcptto'] = ','.join(rcptto)
    print('收件列表：', msg['rcptto'], type(msg['rcptto']))

    msg['Reply-to'] = replyto
    msg['Message-id'] = email.utils.make_msgid()
    msg['Date'] = email.utils.formatdate()

    # 构建alternative的text/plain部分
    textplain = MIMEText('本邮件仅做测试', _subtype='plain', _charset='UTF-8')
    msg.attach(textplain)
    # 构建alternative的text/html部分
    texthtml = MIMEText('这是一封测试', _subtype='html', _charset='UTF-8')
    msg.attach(texthtml)

    try:
        client = smtplib.SMTP_SSL('smtp.mxhichina.com', 465)
        print('服务和端口连通')
    except:
        print('服务和端口不通')
        exit(1)

    # 开启DEBUG模式
    try:
        #client.set_debuglevel(0)
        client.login(username, password)
        print('账密验证成功')
    except:
        print('账密验证失败')
        exit(1)

    client.sendmail(username, msg['rcptto'].split(','), msg.as_string())
    client.quit()
    print('邮件发送成功！')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())